<template>
  <div class="inspection-form-container">
    <!-- 操作栏 -->
    <div class="operation-bar">
      <!-- 根据权限控制新建按钮显示 -->
      <el-button 
        type="primary" 
        @click="openCreateDialog"
        v-if="hasPermission('create')"
      >
        <i class="el-icon-plus"></i> 新建
      </el-button>
      <el-input
        v-model="searchKeyword"
        placeholder="请输入查询内容"
        clearable
        style="width: 300px; margin-left: 20px"
        @keyup.enter="handleSearch"
      ></el-input>
      <el-button type="success" @click="handleSearch" style="margin-left: 10px">
        <i class="el-icon-search"></i> 查询
      </el-button>
      
      <!-- 权限状态提示（实际项目中可移除） -->
      <div class="permission-info" v-if="showPermissionInfo">
        当前权限: 
        <span :class="{ 'permission-enabled': hasPermission('create') }">新建</span> |
        <span :class="{ 'permission-enabled': hasPermission('edit') }">编辑</span> |
        <span :class="{ 'permission-enabled': hasPermission('delete') }">删除</span>
      </div>
    </div>

    <!-- 表格展示 -->
    <el-table
      :data="filteredData"
      border
      stripe
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column prop="id" label="序号" width="80" align="center"></el-table-column>
      <el-table-column label="工单号" prop="workOrderNo" align="center"></el-table-column>
      <el-table-column label="产品代码" prop="productCode" align="center"></el-table-column>
      <el-table-column label="批次号" prop="batchNo" align="center"></el-table-column>
      <el-table-column label="时间段" align="center">
        <template #default="scope">
          {{ scope.row.startTime }} - {{ scope.row.endTime }}
        </template>
      </el-table-column>
      <el-table-column label="检验员" align="center">
        <template #default="scope">
          {{ scope.row.inspectors.join('、') }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template #default="scope">
          <el-tag :type="statusTagType[scope.row.status]">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="quantity" label="数量" align="center"></el-table-column>
      <el-table-column label="操作" width="160" align="center">
        <template #default="scope">
          <el-button
            type="warning"
            size="mini"
            @click="openEditDialog(scope.row)"
            v-if="hasPermission('edit')"
          >
            <i class="el-icon-edit"></i> 编辑
          </el-button>
          <el-button
            type="danger"
            size="mini"
            @click="handleDelete(scope.row.id)"
            style="margin-left: 5px"
            v-if="hasPermission('delete')"
          >
            <i class="el-icon-delete"></i> 删除
          </el-button>
          <span v-if="!hasPermission('edit') && !hasPermission('delete')">-</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新建/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="90%"
      :before-close="handleDialogClose"
      ref="dialogRef"
    >
      <div class="dialog-content">
        <!-- 上部分：新增的基本信息 -->
        <div class="dialog-section">
          <h3 class="section-title">基本信息</h3>
          
          <!-- 第一行：工单号、产品代码、批次号、产品规格、牌号、镀层 -->
          <div class="form-group">
            <el-input
              v-model="baseInfo.workOrderNo"
              placeholder="工单号"
              style="width: 16%; margin-right: 0.5%"
              @keyup.enter="handleWorkOrderEnter"
            ></el-input>
            <el-input
              v-model="baseInfo.productCode"
              placeholder="产品代码"
              style="width: 16%; margin-right: 0.5%"
            ></el-input>
            <el-input
              v-model="baseInfo.batchNo"
              placeholder="批次号"
              style="width: 16%; margin-right: 0.5%"
            ></el-input>
            <el-input
              v-model="baseInfo.productSpec"
              placeholder="产品规格"
              style="width: 16%; margin-right: 0.5%"
            ></el-input>
            <el-input
              v-model="baseInfo.grade"
              placeholder="牌号"
              style="width: 16%; margin-right: 0.5%"
            ></el-input>
            <el-input
              v-model="baseInfo.coating"
              placeholder="镀层"
              style="width: 16%;"
            ></el-input>
          </div>
          
          <!-- 第二行：单重、批次数量、合格数量、批次重量、包材总重 -->
          <div class="form-group">
            <el-input
              v-model.number="baseInfo.unitWeight"
              type="number"
              placeholder="单重"
              min="0"
              style="width: 19%; margin-right: 1%"
            ></el-input>
            <el-input
              v-model.number="baseInfo.batchQuantity"
              type="number"
              placeholder="批次数量"
              min="0"
              style="width: 19%; margin-right: 1%"
            ></el-input>
            <el-input
              v-model.number="baseInfo.qualifiedQuantity"
              type="number"
              placeholder="合格数量"
              min="0"
              style="width: 19%; margin-right: 1%"
            ></el-input>
            <el-input
              v-model.number="baseInfo.batchWeight"
              type="number"
              placeholder="批次重量"
              min="0"
              style="width: 19%; margin-right: 1%"
            ></el-input>
            <el-input
              v-model.number="baseInfo.packagingWeight"
              type="number"
              placeholder="包材总重"
              min="0"
              style="width: 19%;"
            ></el-input>
          </div>
        </div>
        
        <!-- 下部分：原有检验记录部分 -->
        <div class="dialog-section">
          <h3 class="section-title">检验记录</h3>
          <div
            v-for="(row, index) in formRows"
            :key="index"
            class="form-row"
          >
            <!-- 开始日期和时间 -->
            <div style="display: inline-flex; width: 25%;">
              <el-date-picker
                v-model="row.startDate"
                type="date"
                placeholder="开始日期"
                style="width: 48%;"
                :clearable="false"
                @change="calculateTimeDiff(row)"
              ></el-date-picker>
              <el-time-picker
                v-model="row.startTime"
                placeholder="开始时间"
                style="width: 48%; margin-left: 4%;"
                :clearable="false"
                @change="calculateTimeDiff(row)"
              ></el-time-picker>
            </div>

            <!-- 结束日期和时间 -->
            <div style="display: inline-flex; width: 25%; margin-left: 10px;">
              <el-date-picker
                v-model="row.endDate"
                type="date"
                placeholder="结束日期"
                style="width: 48%;"
                :clearable="false"
                @change="calculateTimeDiff(row)"
              ></el-date-picker>
              <el-time-picker
                v-model="row.endTime"
                placeholder="结束时间"
                style="width: 48%; margin-left: 4%;"
                :clearable="false"
                @change="calculateTimeDiff(row)"
              ></el-time-picker>
            </div>

            <el-select
              v-model="row.inspectors"
              multiple
              placeholder="请选择检验员"
              style="width: 15%; margin-left: 10px"
            >
              <el-option
                v-for="item in inspectorOptions"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>

            <el-select
              v-model="row.status"
              placeholder="请选择状态"
              style="width: 8%; margin-left: 10px"
            >
              <el-option
                v-for="item in statusOptions"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>

            <el-input
              v-model.number="row.quantity"
              type="number"
              placeholder="请输入数量"
              min="0"
              style="width: 8%; margin-left: 10px"
            ></el-input>

            <!-- 总时间文本框 -->
            <el-input
              v-model="row.totalTime"
              placeholder="总时间(小时)"
              style="width: 8%; margin-left: 10px"
              readonly
              :disabled="true"
            ></el-input>

            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeRow(index)"
              :disabled="formRows.length <= 1"
              style="margin-left: 10px"
            >删除</el-button>
          </div>

          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="addRow"
            style="margin-top: 10px"
          >
            增加一行
          </el-button>
        </div>
      </div>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { permission } from 'process';

export default {
  data() {
    return {
      tableData: [
        {
          id: 1,
          workOrderNo: 'WO202307001',
          productCode: 'PC001',
          batchNo: 'B202307001',
          productSpec: 'Φ10×20mm',
          grade: '304',
          coating: 'Zn',
          unitWeight: 0.5,
          batchQuantity: 1000,
          qualifiedQuantity: 980,
          batchWeight: 500,
          packagingWeight: 50,
          startTime: '2023-07-01 08:00',
          endTime: '2023-07-01 12:00',
          inspectors: ['张三', '李四'],
          status: '已完成',
          quantity: 25,
          totalTime: '4.00'
        },
        {
          id: 2,
          workOrderNo: 'WO202307002',
          productCode: 'PC002',
          batchNo: 'B202307002',
          productSpec: 'Φ12×25mm',
          grade: '316',
          coating: 'Ni',
          unitWeight: 0.8,
          batchQuantity: 800,
          qualifiedQuantity: 790,
          batchWeight: 640,
          packagingWeight: 60,
          startTime: '2023-07-01 13:00',
          endTime: '2023-07-01 17:00',
          inspectors: ['王五'],
          status: '待处理',
          quantity: 18,
          totalTime: '4.00'
        }
      ],
      searchKeyword: '',
      dialogVisible: false,
      dialogTitle: '新建记录',
      currentEditId: null,
      PermissionAll:[],
      // 基本信息部分
      baseInfo: {
        workOrderNo: '',
        productCode: '',
        batchNo: '',
        productSpec: '',
        grade: '',
        coating: '',
        unitWeight: null,
        batchQuantity: null,
        qualifiedQuantity: null,
        batchWeight: null,
        packagingWeight: null
      },
      // 检验记录部分（日期和时间分开存储）
      formRows: [
        {
          startDate: null,    // 开始日期
          startTime: null,    // 开始时间
          endDate: null,      // 结束日期
          endTime: null,      // 结束时间
          inspectors: [],
          status: '',
          quantity: null,
          totalTime: ''
        }
      ],
      inspectorOptions: ['张三', '李四', '王五', '赵六'],
      statusOptions: ['待处理', '处理中', '已完成', '已取消'],
      statusTagType: {
        '待处理': 'info',
        '处理中': 'warning',
        '已完成': 'success',
        '已取消': 'danger'
      },
      permissions: {
        create: true,
        edit: true,
        delete: true
      },
      showPermissionInfo: true
    };
  },
  computed: {
    filteredData() {
      if (!this.searchKeyword) return this.tableData;
      
      const keyword = this.searchKeyword.toLowerCase();
      return this.tableData.filter(item => {
        const baseInfoMatch = item.workOrderNo.toLowerCase().includes(keyword) ||
                             item.productCode.toLowerCase().includes(keyword) ||
                             item.batchNo.toLowerCase().includes(keyword) ||
                             item.productSpec.toLowerCase().includes(keyword) ||
                             item.grade.toLowerCase().includes(keyword) ||
                             item.coating.toLowerCase().includes(keyword);
                             
        const timeMatch = item.startTime.toLowerCase().includes(keyword) || 
                         item.endTime.toLowerCase().includes(keyword);
                         
        const inspectorMatch = item.inspectors.some(ins => 
          ins.toLowerCase().includes(keyword)
        );
        
        const statusMatch = item.status.toLowerCase().includes(keyword);
        const quantityMatch = item.quantity.toString().includes(keyword);
        
        return baseInfoMatch || timeMatch || inspectorMatch || statusMatch || quantityMatch;
      });
    }
  },
  methods: {
    testBtton(){

    },
    get_gx_detail_all(){
      console.log("DDDD")
      this.inspectorOptions = []
      this.statusOptions = []
      // 注意：原代码中http未定义，实际项目需确保this.http已挂载（如axios）
      this.http.get('api/ak_wgjy_sgd_peizhi/search_gx_detail',
                          {}).then((reslut) => {
                            console.log(reslut)
                            for(let i=0;i<reslut["rows"].length;i++){
                              var per_ = reslut["rows"][i]
                              if(per_["type"] == "工序"){
                                this.statusOptions.push(per_["name"])
                              }else{
                                this.inspectorOptions.push(per_["name"])
                              }
                            }
                        }).catch((error) => {
                            console.error('同步失败:', error);
                        });
        //  {
        //   id: 2,
        //   workOrderNo: 'WO202307002',
        //   productCode: 'PC002',
        //   batchNo: 'B202307002',
        //   productSpec: 'Φ12×25mm',
        //   grade: '316',
        //   coating: 'Ni',
        //   unitWeight: 0.8,
        //   batchQuantity: 800,
        //   qualifiedQuantity: 790,
        //   batchWeight: 640,
        //   packagingWeight: 60,
        //   startTime: '2023-07-01 13:00',
        //   endTime: '2023-07-01 17:00',
        //   inspectors: ['王五'],
        //   status: '待处理',
        //   quantity: 18,
        //   totalTime: '4.00'
        // }
      this.tableData = []
      this.http.get('api/ak_wgjy_sgd_peizhi/search_info_db',
                          {}).then((reslut) => {
                            console.log(reslut)
                            for(let i=0;i<reslut["rows"].length;i++){
                              var per_ = reslut["rows"][i]
                              per_["id"] = i+1
                              per_["inspectors"] = per_["inspectors"].split(', ')
                              this.tableData.push(per_)
                            }
                        }).catch((error) => {
                            console.error('同步失败:', error);
                        });
    },
    // 工单号回车事件处理
    handleWorkOrderEnter() {
      console.log('有回车',this.baseInfo.workOrderNo);
      this.$message.info('检测到工单号输入框的回车事件');
      this.http.get('api/table_wgjy/SyncProductionTask_wgjy_get',
                          {name_order:this.baseInfo.workOrderNo}).then((reslut) => {
                          console.log("GGGGG");
                          console.log('同步成功:', reslut);
                          this.baseInfo.productCode = reslut["rows"][0]["product"]
                          this.baseInfo.batchNo = reslut["rows"][0]["raw_lot_id"]
                          this.baseInfo.productSpec = reslut["rows"][0]["prodcut_spec"]
                          this.baseInfo.grade = reslut["rows"][0]["grade"]
                          this.baseInfo.unitWeight = reslut["rows"][0]["piece_weight"]
                          
                        }).catch((error) => {
                            console.error('同步失败:', error);
                        });
    },
    
    // 权限检查方法
    hasPermission(permission) {
      return this.permissions[permission] === true;
    },
    
    openCreateDialog() {
      if (!this.hasPermission('create')) {
        this.$message.error('您没有新建权限，请联系管理员');
        return;
      }
      
      this.dialogTitle = '新建记录';
      this.currentEditId = null;
      this.resetFormData();
      this.$nextTick(() => {
        this.dialogVisible = true;
      });
    },
    
    openEditDialog(row) {
      if (!this.hasPermission('edit')) {
        this.$message.error('您没有编辑权限，请联系管理员');
        return;
      }
      
      this.dialogTitle = '编辑记录';
      this.currentEditId = row.id;
      this.resetFormData();
      
      // 填充基本信息
      this.baseInfo = {
        workOrderNo: row.workOrderNo,
        productCode: row.productCode,
        batchNo: row.batchNo,
        productSpec: row.productSpec,
        grade: row.grade,
        coating: row.coating,
        unitWeight: row.unitWeight,
        batchQuantity: row.batchQuantity,
        qualifiedQuantity: row.qualifiedQuantity,
        batchWeight: row.batchWeight,
        packagingWeight: row.packagingWeight
      };
      
      // 解析开始时间为日期和时间
      const startDateTime = new Date(row.startTime);
      const endDateTime = new Date(row.endTime);
      
      // 填充检验记录
      this.formRows[0] = {
        startDate: new Date(startDateTime.getFullYear(), startDateTime.getMonth(), startDateTime.getDate()),
        startTime: new Date(startDateTime),
        endDate: new Date(endDateTime.getFullYear(), endDateTime.getMonth(), endDateTime.getDate()),
        endTime: new Date(endDateTime),
        inspectors: [...row.inspectors],
        status: row.status,
        quantity: row.quantity,
        totalTime: row.totalTime
      };
      
      this.$nextTick(() => {
        this.calculateTimeDiff(this.formRows[0]);
        this.dialogVisible = true;
      });
    },
    
    // 重置表单数据（设置日期默认值为当天）
    resetFormData() {
      // 重置基本信息
      this.baseInfo = {
        workOrderNo: '',
        productCode: '',
        batchNo: '',
        productSpec: '',
        grade: '',
        coating: '',
        unitWeight: null,
        batchQuantity: null,
        qualifiedQuantity: null,
        batchWeight: null,
        packagingWeight: null
      };
      
      // 获取当天日期
      const today = new Date();
      const defaultDate = new Date(today.getFullYear(), today.getMonth(), today.getDate());
      
      // 重置检验记录
      this.formRows = [
        {
          startDate: defaultDate,
          startTime: new Date(today.getFullYear(), today.getMonth(), today.getDate(), 8, 0, 0),
          endDate: defaultDate,
          endTime: new Date(today.getFullYear(), today.getMonth(), today.getDate(), 12, 0, 0),
          inspectors: [],
          status: '',
          quantity: null,
          totalTime: ''
        }
      ];
      
      // 计算初始总时间
      this.$nextTick(() => {
        this.calculateTimeDiff(this.formRows[0]);
      });
    },
    
    // 新增检验记录行（默认当天日期）
    addRow() {
      const today = new Date();
      const defaultDate = new Date(today.getFullYear(), today.getMonth(), today.getDate());
      
      const newRow = {
        startDate: defaultDate,
        startTime: new Date(today.getFullYear(), today.getMonth(), today.getDate(), 8, 0, 0),
        endDate: defaultDate,
        endTime: new Date(today.getFullYear(), today.getMonth(), today.getDate(), 12, 0, 0),
        inspectors: [],
        status: '',
        quantity: null,
        totalTime: ''
      };
      
      this.formRows.push(newRow);
      
      // 计算新增行的初始总时间
      this.$nextTick(() => {
        this.calculateTimeDiff(newRow);
      });
    },
    
    removeRow(index) {
      this.formRows.splice(index, 1);
    },
    
    handleSearch() {
      console.log('搜索关键词:', this.searchKeyword);
    },
    
    handleDelete(id) {
      if (!this.hasPermission('delete')) {
        this.$message.error('您没有删除权限，请联系管理员');
        return;
      }
      
      this.$confirm('确定要删除这条记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableData = this.tableData.filter(item => item.id !== id);
        this.$message.success('删除成功');
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    
    submitForm() {
      // 权限检查
      if (this.currentEditId && !this.hasPermission('edit')) {
        this.$message.error('您没有编辑权限，请联系管理员');
        return;
      }
      
      if (!this.currentEditId && !this.hasPermission('create')) {
        this.$message.error('您没有新建权限，请联系管理员');
        return;
      }
      
      if (!this.validateForm()) {
        return;
      }
      
      if (this.currentEditId) {
        // 编辑操作
        const index = this.tableData.findIndex(item => item.id === this.currentEditId);
        if (index !== -1) {
          const row = this.formRows[0];
          this.tableData[index] = {
            ...this.tableData[index],
            ...this.baseInfo,
            startTime: this.formatDateTime(row.startDate, row.startTime),
            endTime: this.formatDateTime(row.endDate, row.endTime),
            inspectors: row.inspectors,
            status: row.status,
            quantity: row.quantity,
            totalTime: row.totalTime
          };
          this.updateWorkOrder(this.tableData[index],"编辑");
          this.$message.success('编辑成功');
        }
      } else {
        var in_befoer = this.tableData.length;
        // 新建操作
        this.formRows.forEach(row => {
          const newId = Math.max(...this.tableData.map(item => item.id), 0) + 1;
          const newRecord = {
            id: newId,
            ...this.baseInfo,
            startTime: this.formatDateTime(row.startDate, row.startTime),
            endTime: this.formatDateTime(row.endDate, row.endTime),
            inspectors: row.inspectors,
            status: row.status,
            quantity: row.quantity,            
            totalTime: row.totalTime
          };
          this.tableData.push(newRecord);
        });
        var in_after = this.tableData.length;
        console.log(">>>",this.tableData);
        var all_info = [];
        for(let i=0;i<(in_after-in_befoer);i++){
          console.log(in_befoer+i,this.tableData[in_befoer+i]);
          var per = this.tableData[in_befoer+i];
          var per_info = {
            workOrderNo:per["workOrderNo"],
            productCode:per["productCode"],
            batchNo:per["batchNo"],
            productSpec:per["productSpec"],
            grade:per["grade"],
            coating:per["coating"],
            unitWeight:per["unitWeight"],
            batchQuantity:per["batchQuantity"],
            qualifiedQuantity:per["qualifiedQuantity"],
            batchWeight:per["batchWeight"],
            packagingWeight:per["packagingWeight"],
            startTime: per["startTime"],
            endTime: per["endTime"],
            inspectors: per["inspectors"],
            status:per["status"],
            quantity:per["quantity"],
            totalTime:per["totalTime"],
          };
          all_info.push(per_info);
        }
        console.log("9999999",all_info);
        this.updateWorkOrder(all_info,"创建");
        this.$message.success('创建成功');
      }      
      this.dialogVisible = false;
    },
    
    updateWorkOrder(workOrder,option) {
      try {
        console.log(workOrder,option);
        let jsonString_mes_data = JSON.stringify(workOrder);
        const loadingInstance = this.$loading({
                    lock: true,
                    text: '提交'+option+'申请中...', 
                    spinner: 'el-icon-loading',
                    background: 'rgba(247, 237, 237, 0.7)'
                });                
                this.http.get('api/ak_wgjy_sgd_peizhi/insert_info_gx',
                    {option:option,mes_data:jsonString_mes_data})
                    .then((reslut) => {
                    loadingInstance.close(); 
                    if(reslut == "成功"){
                        this.$message.success('工单已成功更新');
                    }
                    })
                    .catch((error) => {
                    console.log("失败", error);
                    loadingInstance.close();    
                    this.$message.error('工单更新失败，请重试');                        
                    });
 
      } catch (error) {
        console.error('更新工单失败：', error);
        this.$message.error('更新工单失败，请稍后重试');
      }
    },
    
    validateForm() {
      // 验证基本信息
      if (!this.baseInfo.workOrderNo) {
        this.$message.error('请输入工单号');
        return false;
      }
      
      if (!this.baseInfo.productCode) {
        this.$message.error('请输入产品代码');
        return false;
      }
      
      if (!this.baseInfo.batchNo) {
        this.$message.error('请输入批次号');
        return false;
      }
      
      // 验证检验记录
      for (let i = 0; i < this.formRows.length; i++) {
        const row = this.formRows[i];
        
        // 验证日期和时间
        if (!row.startDate) {
          this.$message.error(`第${i+1}行检验记录：请选择开始日期`);
          return false;
        }
        
        if (!row.startTime) {
          this.$message.error(`第${i+1}行检验记录：请选择开始时间`);
          return false;
        }
        
        if (!row.endDate) {
          this.$message.error(`第${i+1}行检验记录：请选择结束日期`);
          return false;
        }
        
        if (!row.endTime) {
          this.$message.error(`第${i+1}行检验记录：请选择结束时间`);
          return false;
        }
        
        if (!row.inspectors || row.inspectors.length === 0) {
          this.$message.error(`第${i+1}行检验记录：请选择检验员`);
          return false;
        }
        
        if (!row.status) {
          this.$message.error(`第${i+1}行检验记录：请选择状态`);
          return false;
        }
        
        if (row.quantity === null || row.quantity < 0) {
          this.$message.error(`第${i+1}行检验记录：请输入有效的数量`);
          return false;
        }
        
        // 验证总时间
        if (!row.totalTime || isNaN(parseFloat(row.totalTime))) {
          this.$message.error(`第${i+1}行检验记录：时间范围异常，请重新选择`);
          return false;
        }
      }
      
      return true;
    },
    
    handleDialogClose() {
      this.resetFormData();
      this.dialogVisible = false;
    },
    
    // 格式化日期和时间为字符串
    formatDateTime(date, time) {
      if (!(date instanceof Date) || !(time instanceof Date)) return '';
      
      const year = date.getFullYear();
      const month = this.padZero(date.getMonth() + 1);
      const day = this.padZero(date.getDate());
      const hours = this.padZero(time.getHours());
      const minutes = this.padZero(time.getMinutes());
      
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
    
    padZero(num) {
      return num < 10 ? `0${num}` : num;
    },
    
    // 计算时间差（小时）
    calculateTimeDiff(row) {
      // 检查日期和时间是否完整
      if (!(row.startDate instanceof Date) || !(row.startTime instanceof Date) ||
          !(row.endDate instanceof Date) || !(row.endTime instanceof Date)) {
        row.totalTime = '';
        return;
      }
      
      // 组合日期和时间
      const startTime = new Date(
        row.startDate.getFullYear(),
        row.startDate.getMonth(),
        row.startDate.getDate(),
        row.startTime.getHours(),
        row.startTime.getMinutes(),
        row.startTime.getSeconds()
      );
      
      const endTime = new Date(
        row.endDate.getFullYear(),
        row.endDate.getMonth(),
        row.endDate.getDate(),
        row.endTime.getHours(),
        row.endTime.getMinutes(),
        row.endTime.getSeconds()
      );
      
      // 防止开始时间大于结束时间
      if (startTime > endTime) {
        this.$message.warning('开始时间不能晚于结束时间');
        row.totalTime = '';
        return;
      }
      
      // 计算毫秒差，转换为小时（保留2位小数）
      const diffMs = endTime - startTime;
      const diffHours = (diffMs / 3600000).toFixed(2); // 1小时 = 3600000毫秒
      
      // 赋值给总时间字段
      row.totalTime = diffHours;
    }
  },
  created() {
    this.get_gx_detail_all();
    console.log("初始化完成");
    console.log(this.$store.getters.getPermission('/suigd'))   //对应账号权限获取
    var permission = this.$store.getters.getPermission('/suigd')
    this.PermissionAll = permission["permission"]
    console.log("???this.PermissionAll",this.PermissionAll)
    console.log(this.$store.getters.getUserInfo())
  }
};
</script>

<style scoped>
.inspection-form-container {
  padding: 20px;
  background-color: #fff;
  min-height: 500px;
}

.operation-bar {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

/* 对话框样式调整 */
.dialog-content {
  max-height: 600px;
  overflow-y: auto;
  padding-right: 10px;
}

.dialog-section {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.dialog-section:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.section-title {
  margin-bottom: 15px;
  color: #333;
  font-size: 16px;
  font-weight: 500;
  padding-left: 5px;
  border-left: 3px solid #42b983;
}

.form-group {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 15px;
}

.form-row {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px dashed #e5e5e5;
  flex-wrap: wrap; /* 适配小屏幕 */
}

.form-row:last-child {
  border-bottom: none;
}

/* 权限信息样式 */
.permission-info {
  margin-left: auto;
  color: #666;
  font-size: 12px;
  padding: 5px 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.permission-enabled {
  color: #42b983;
  font-weight: bold;
}

/* 总时间输入框样式 */
.el-input[readonly] {
  background-color: #f5f7fa;
  color: #666;
}
</style>
